module Manage::FoldersHelper

  def order_folders
    fid = @folder.id
    fid = Folder.find(:first, :conditions => "top_level is true").id unless @folder.id
    rvalue = %(<ul id="folders">)
    FolderContent.content_for(fid) do |content|
      rvalue << %(<li id="top_level_#{content.id}">&nbsp;&nbsp;)
      if content.sub_folder
        rvalue << link_to(content.sub_folder.name, :action => 'index', :id => content.sub_folder.id)
      elsif content.function
        rvalue << "Function: " << h(content.function.name)
      else
        rvalue << "Page: " << h(content.page.title)
      end
      rvalue << "</li>"
    end
    rvalue << "</ul>"
    rvalue << sortable_element("folders", :complete => visual_effect(:hightlight, "folders"),:url => {:action => 'index', :commit => 'reorder'})
    rvalue
  end

  def folder_tree
    topfldr = Folder.find(:first, :conditions => "top_level is true")
    rvalue = %(<div id="folder_tree"><br/><span style="font-size: 10pt; font-weight: bold;">Folder Tree</span><br/>)
    rvalue << %(<ul>)
    topfldr.sub_folder.each do |fldr|
      rvalue << folder_children(fldr)
    end
    rvalue << %(</ul></div>)
  end

  private

    def folder_children(fldr)
      subs =  fldr.sub_folder.length > 0
      rvalue = %(<li>#{h(fldr.name)}&nbsp;&nbsp;#{get_folder_links(fldr,subs)})
      if subs
        rvalue << %(<ul class="tree_group" id="tree_folder_#{fldr.id}" style="display: none;">)
        fldr.sub_folder.each do |sfldr|
          rvalue << folder_children(sfldr)
        end
        rvalue << %(</ul>)
      end
      rvalue << %(</li>)
      rvalue
    end

    def get_folder_links(fldr,subs)
      links = %(<span style="font-size: 8pt">[<a href="/manage/folders/index/#{fldr.id}">edit</a>)
      links << %( | <a href="#" onclick="show_tree_folder(#{fldr.id})">toggle</a>) if subs
      links << %(]</span>)
      links
    end
end
